package com.newx.limit.manage.impl;

import com.google.common.collect.Maps;
import com.google.common.util.concurrent.RateLimiter;
import com.newx.limit.entity.Limiter;
import com.newx.limit.manage.LimiterManager;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author yxl
 * @date 2024/7/5 0005 17:23
 */
@Slf4j
public class GuavaLimiter implements LimiterManager {

    private final Map<String, RateLimiter> limiterMap = Maps.newConcurrentMap();

    @Override
    public boolean tryAccess(Limiter limiter) {
        RateLimiter rateLimiter = getRateLimiter(limiter);
        if (rateLimiter == null) {
            return false;
        }
        // 拿令牌
        boolean access = rateLimiter.tryAcquire(1,limiter.getSeconds(), TimeUnit.SECONDS);
        log.info("{} access :{}",limiter.getKey() , access);
        return access;
    }

    private RateLimiter getRateLimiter(Limiter limiter) {
        //key作用：不同的接口，不同的流量控制
        String key=limiter.getKey();
        RateLimiter rateLimiter = null;
        //验证缓存是否有命中key
        if (!limiterMap.containsKey(key)) {
            // 创建令牌桶
            rateLimiter = RateLimiter.create(limiter.getLimitNum());
            limiterMap.put(key, rateLimiter);
            log.info("Guava新建了令牌桶={}，容量={}",key,limiter.getLimitNum());
        }
        rateLimiter = limiterMap.get(key);
        return rateLimiter;
    }
}
